package cate.game.pvp.guildwar.data.base;

import cate.common.util.XT;
import cate.game.pvp.guildwar.data.GWGuildProfile;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;


@NoteClass("公会战对阵信息")
@Slf4j
public class GWMatch {

    @NoteField("对阵列表")
    public List<GWMatchGroup> matchList;

    @NoteField("接受过哪些game服的报名信息")
    public Set<Integer> srvIds;

    @NoteField("报名的公会列表")
    public Map<String, GWGuildProfile> guildMap;


    public void initialize() {
        if (matchList == null) {
            matchList = new ArrayList<>();
        }
        if (srvIds == null) {
            srvIds = new HashSet<>();
        }
        if (guildMap == null) {
            guildMap = new HashMap<>();
        }
    }

    /**
     * 处理game服的报名信息
     *
     */
    public void handleSign(int srvId, List<GWGuildProfile> list) {
        if (srvIds.contains(srvId)) {
            log.info("接收到{}服的公会战报名信息,但是已经报名过了", srvId);
            return;
        }
        srvIds.add(srvId);
        for (GWGuildProfile p : list) {
            guildMap.put(p.uid,p);
        }
        log.info("接收到[{}服]的公会战的报名信息,一共上报了{}个公会",srvId, list.size());
    }

    /** 进行分组 */
    public void buildMatchList() {
        matchList.clear();
        List<GWGuildProfile> signList = new ArrayList<>(guildMap.values());
        if (XT.isBlank(signList)) {
            log.info("[公会战]本次公会战分组失败 因为没有任何报名的公会");
            return;
        }
        int guildNum = signList.size();
        // 如果有奇数个公会报名 那就选择一个公会轮空
        if (guildNum % 2 == 1) {
            int i = XT.randomIndex(guildNum);
            GWGuildProfile guild = signList.get(i);
            GWMatchGroup matchGroup = new GWMatchGroup();
            matchGroup.a = guild;
            matchGroup.b = null;
            matchList.add(matchGroup);
            signList.remove(i);
            log.info("公会战 公会[{}]轮空", guild.name);
        }
        Collections.shuffle(signList);
        signList = signList.stream().sorted(Comparator.comparing(a -> -a.point)).collect(Collectors.toList());
        int group = signList.size() / 2;
        for (int i = 1; i <= group; i++) {
            GWMatchGroup matchGroup = new GWMatchGroup();
            matchGroup.a = signList.get(2 * i - 2);
            matchGroup.b = signList.get(2 * i - 1);
            matchList.add(matchGroup);
        }
        log.info("公会战分组完毕,本次比赛共有{}组", matchList.size());
    }

    public void clear() {
        matchList.clear();
        srvIds.clear();
        guildMap.clear();
    }
}
